<template>
  <div class="h-full w-full p-6 bg-gray-50">
    <div class="max-w-6xl mx-auto">
      <!-- 页面标题 -->
      <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-900">知识新增</h1>
        <p class="text-gray-600 mt-2">上传文档进行实体关系抽取</p>
      </div>

      <!-- 文件上传区域 -->
      <div v-if="!textChunks.length" class="bg-white rounded-lg shadow-sm p-6">
        <h3 class="text-lg font-semibold mb-4">上传文档</h3>
        <a-upload-dragger
          v-model:fileList="fileList"
          :before-upload="beforeUpload"
          :custom-request="handleUpload"
          accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
          :multiple="false"
          class="mb-4"
        >
          <p class="ant-upload-drag-icon">
            <span class="icon-[mdi--cloud-upload] text-4xl text-blue-500"></span>
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p class="ant-upload-hint">支持 PDF、Word、Excel 格式文件，单个文件大小不超过 50MB</p>
        </a-upload-dragger>

        <!-- 上传进度 -->
        <div v-if="uploading" class="mb-4">
          <a-progress :percent="uploadProgress" />
          <p class="text-sm text-gray-600 mt-2">正在上传并解析文档...</p>
        </div>
      </div>

      <!-- 文本切片展示区域 -->
      <div
        v-if="textChunks.length && !generating && !generateSuccess"
        class="bg-white rounded-lg shadow-sm p-6"
      >
        <div class="flex justify-between items-center mb-4">
          <div>
            <h3 class="text-lg font-semibold">文档切片内容</h3>
            <p class="text-sm text-gray-500 mt-1">
              已解析 {{ currentFileType.toUpperCase() }} 文档，共 {{ textChunks.length }} 个切片
            </p>
          </div>
          <div class="space-x-2">
            <a-button @click="resetUpload">重新上传</a-button>
            <a-button type="primary" @click="generateGraph">实体关系抽取</a-button>
          </div>
        </div>

        <div class="space-y-3 max-h-[400px] 2xl:max-h-[600px] overflow-y-auto">
          <div
            v-for="(chunk, index) in textChunks"
            :key="index"
            class="p-3 bg-gray-50 rounded-lg border-l-4 border-blue-500 group hover:bg-gray-100 transition-colors"
          >
            <div class="flex justify-between items-start mb-2">
              <div class="flex items-center space-x-2">
                <span class="text-xs text-gray-500">切片 {{ index + 1 }}</span>
                <span class="text-xs text-blue-600">{{ currentFileType.toUpperCase() }}</span>
              </div>
              <a-button
                type="text"
                size="small"
                danger
                @click="deleteChunk(index)"
                class="opacity-0 group-hover:opacity-100 transition-opacity !flex !items-center"
                :disabled="textChunks.length <= 1"
              >
                <template #icon>
                  <span class="icon-[mdi--delete] text-red-500"></span>
                </template>
                删除
              </a-button>
            </div>
            <p class="text-sm text-gray-700 leading-relaxed">{{ chunk }}</p>
          </div>
        </div>
      </div>

      <!-- 生成图谱进度 -->
      <div v-if="generating" class="bg-white rounded-lg shadow-sm p-6">
        <div class="text-center py-12">
          <a-spin size="large" />
          <p class="text-lg font-medium mt-4">正在进行实体关系抽取...</p>
          <p class="text-gray-600 mt-2">这可能需要几分钟时间，请耐心等待</p>
          <a-progress :percent="generateProgress" class="mt-4 max-w-md mx-auto" />
        </div>
      </div>

      <!-- 生成成功 -->
      <div v-if="generateSuccess" class="bg-white rounded-lg shadow-sm p-6">
        <div class="text-center">
          <a-result
            status="success"
            title="实体关系抽取成功"
            sub-title="已成功从文档中提取实体和关系，可以前往审核页面进行审核"
          >
            <template #extra>
              <div class="space-x-2">
                <a-button type="primary" @click="goToAudit">前往审核</a-button>
                <a-button @click="resetProcess">重新开始</a-button>
              </div>
            </template>
          </a-result>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { message } from 'ant-design-vue'
import { h } from 'vue'
import { data } from './data.js'

const fileList = ref([])
const uploading = ref(false)
const uploadProgress = ref(0)
const generating = ref(false)
const generateProgress = ref(0)
const generateSuccess = ref(false)

// 文本切片数据
const textChunks = ref([])

// 添加当前文件类型的响应式变量
const currentFileType = ref('')

// 文件上传前验证
const beforeUpload = (file) => {
  const isValidType = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  ].includes(file.type)

  if (!isValidType) {
    message.error('只支持 PDF、Word、Excel、PPT 格式文件！')
    return false
  }

  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    message.error('文件大小不能超过 50MB！')
    return false
  }

  // return false // 阻止默认上传，使用自定义上传
}

// 获取文件类型的辅助函数
const getFileType = (fileName) => {
  const name = fileName.toLowerCase()
  if (name.includes('.ppt') || name.includes('.pptx')) {
    return 'ppt'
  } else if (name.includes('.doc') || name.includes('.docx')) {
    return 'word'
  } else if (name.includes('.pdf')) {
    return 'pdf'
  }
  return 'unknown'
}

// 处理文档切片数据
const processChunks = (rawData, fileType) => {
  if (!rawData || !Array.isArray(rawData)) {
    return []
  }

  // 将数组数据合并成字符串，然后按逗号分隔
  const combinedText = rawData.join(',')

  // 按逗号分隔并清理数据
  const chunks = combinedText
    .split(',')
    .map(chunk => chunk.trim())
    .filter(chunk => chunk.length > 0 && chunk !== '...')  // 过滤空内容和省略号
    .slice(0, 50)  // 限制显示数量，避免过多

  return chunks
}

// 自定义上传处理
const handleUpload = async () => {
  if (!fileList.value.length) {
    message.error('请选择要上传的文件！')
    return
  }

  uploading.value = true
  uploadProgress.value = 0

  const progressInterval = setInterval(() => {
    if (uploadProgress.value < 90) {
      uploadProgress.value += parseInt(Math.random() * 15)
    }
  }, 300)

  try {
    await new Promise((resolve) => setTimeout(resolve, 3000))

    clearInterval(progressInterval)
    uploadProgress.value = 100

    // 获取文件信息
    const file = fileList.value[0]
    const fileType = getFileType(file.name)
    currentFileType.value = fileType  // 设置当前文件类型

    console.log(`检测到文件类型: ${fileType}，文件名: ${file.name}`)

    // 根据文件类型获取对应数据
    let rawData = []
    switch (fileType) {
      case 'ppt':
        rawData = data.ppt || []
        break
      case 'word':
        rawData = data.word || []
        break
      case 'pdf':
        rawData = data.pdf || []
        break
      default:
        rawData = data.ppt || []  // 默认使用ppt数据
    }

    // 处理切片数据
    textChunks.value = processChunks(rawData, fileType)

    console.log(`生成了 ${textChunks.value.length} 个文档切片`)

    message.success(`文件上传成功，已生成 ${textChunks.value.length} 个文本切片！`)
  } catch (error) {
    clearInterval(progressInterval)
    console.error('上传失败:', error)
    message.error('文件上传失败！')
  } finally {
    uploading.value = false
  }
}

// 重新上传
const resetUpload = () => {
  fileList.value = []
  textChunks.value = []
  currentFileType.value = ''  // 重置文件类型
  generateSuccess.value = false
  uploadProgress.value = 0
  generateProgress.value = 0
}

// 生成图谱
const generateGraph = async () => {
  generating.value = true
  generateProgress.value = 0

  // 模拟生成进度
  const progressInterval = setInterval(() => {
    if (generateProgress.value < 90) {
      generateProgress.value += parseInt(Math.random() * 15)
    }
  }, 500)

  try {
    // 这里应该调用实际的图谱生成API，将文本切片发送到后端进行实体关系抽取
    await new Promise((resolve) => setTimeout(resolve, 5000))

    clearInterval(progressInterval)
    generateProgress.value = 100

    // 准备要传递给审核页面的数据
    const extractedData = {
      fileName: fileList.value[0]?.name || '未知文档',
      fileType: currentFileType.value,
      uploadTime: new Date().toLocaleString(),
      chunksCount: textChunks.value.length,
      // 模拟从文档切片中提取的实体关系数据
      extractedRelations: generateMockRelations()
    }

    // 将数据存储到sessionStorage，供审核页面使用
    sessionStorage.setItem('latestExtractedData', JSON.stringify(extractedData))

    // 显示成功界面，而不是直接跳转
    generateSuccess.value = true
    message.success('实体关系抽取完成！')
  } catch (error) {
    clearInterval(progressInterval)
    message.error('知识抽取失败！')
  } finally {
    generating.value = false
  }
}

// 更智能的模拟实体关系生成 - 基于真实数据
const generateMockRelations = () => {
  const fileName = fileList.value[0]?.name || '未知文档'
  const currentTime = new Date().toISOString().split('T')[0]
  const relations = []

  // 基于data.js真实数据的实体和关系模板
  const entityTemplates = {
    ppt: [
      { entity1: '供应链管理', relation: '包含', entity2: '质量控制' },
      { entity1: '沈哲', relation: '负责', entity2: '供应链管理' },
      { entity1: '21世纪企业', relation: '面临', entity2: '环境变化' },
      { entity1: '顾客需求', relation: '影响', entity2: '企业竞争' },
      { entity1: '跨国公司', relation: '占有', entity2: '全球贸易' },
      { entity1: '技术进步', relation: '推动', entity2: '产品更新' },
      { entity1: '全球化战略', relation: '要求', entity2: '技术支持' },
      { entity1: '市场竞争', relation: '促进', entity2: '服务改进' }
    ],
    word: [
      { entity1: '质检部门', relation: '执行', entity2: 'ISO9001标准' },
      { entity1: '责任工程师', relation: '处理', entity2: '质量问题' },
      { entity1: '供应商', relation: '提供', entity2: '核心组件' },
      { entity1: '质量体系', relation: '确保', entity2: '产品合格' },
      { entity1: '检测流程', relation: '建立', entity2: '追溯体系' },
      { entity1: '改进措施', relation: '防止', entity2: '问题重现' }
    ],
    pdf: [
      { entity1: '汽车制造业', relation: '依赖', entity2: '零部件供应商' },
      { entity1: '质量管理', relation: '影响', entity2: '整车安全' },
      { entity1: '供应商评估', relation: '包含', entity2: '现场审核' },
      { entity1: '质量认证', relation: '要求', entity2: '样品测试' },
      { entity1: '快速响应', relation: '确保', entity2: '问题处理' },
      { entity1: '生产部门', relation: '负责', entity2: '质量监控' }
    ]
  }

  const templates = entityTemplates[currentFileType.value] || entityTemplates.ppt
  const chunks = textChunks.value.slice(0, templates.length)

  templates.forEach((template, index) => {
    const relation = {
      id: Date.now() + index,
      source: fileName,
      entity1: template.entity1,
      relation: template.relation,
      entity2: template.entity2,
      chunk: chunks[index] || `从${fileName}中提取的文本片段${index + 1}`,
      tags: [getDocumentTag()],
      status: 'pending',
      createTime: currentTime,
    }
    relations.push(relation)
  })

  return relations
}

// 根据文档类型获取标签
const getDocumentTag = () => {
  switch (currentFileType.value) {
    case 'pdf':
      return 'PDF文档'
    case 'word':
      return 'Word文档'
    case 'ppt':
      return 'PPT文档'
    default:
      return '文档'
  }
}

// 跳转到审核页面
const goToAudit = () => {
  window.location.href = '#/graph/audit'
}

// 重新开始
const resetProcess = () => {
  fileList.value = []
  textChunks.value = []
  generateSuccess.value = false
  uploadProgress.value = 0
  generateProgress.value = 0
}

// 删除文本切片
const deleteChunk = (index) => {
  if (textChunks.value.length <= 1) {
    message.warning('至少需要保留一个段落！')
    return
  }

  const deletedChunk = textChunks.value[index]
  textChunks.value.splice(index, 1)

  messag
e.success(`已删除切片 ${index + 1}，剩余 ${textChunks.value.length} 个切片`)

  // 如果需要，可以在这里添加日志记录
  console.log(`删除了切片: ${deletedChunk.substring(0, 50)}...`)
}
</script>

<style lang="scss" scoped>
.ant-upload-drag-icon {
  margin-bottom: 16px;
}
</style>

